'use strict';

angular.module('CBO').controller('DeviceMonitorInfosController', ['$scope', 'BaseModule', 'BaseEnum', 'CBOEnum', 'BaseConst', 'BaseFunction', 'Authentication',
    function($scope, BaseModule, BaseEnum, CBOEnum, BaseConst, BaseFunction, Authentication) {
        $scope.ExecuteResultEnum = CBOEnum.ExecuteResult;

        BaseModule.initModule($scope, 'Department');
        BaseModule.initModule($scope, 'WorkLocation');
        BaseModule.initModule($scope, 'StationTerminal');
        BaseModule.initModule($scope, 'StationWork');
        BaseModule.initModule($scope, 'DeviceMonitor');

        $scope.Department = null;
        $scope.FocusedRecord = null;

        function getChildDepartmentIds(departmentIds, returnFun){
            $scope.Module.Department.find(
                {
                    ParentDepartment: {$in: departmentIds}
                },
                null, null, function(records){
                    var departments = [];
                    if(records.length > 0){
                        for(var i=0; i<records.length; i++){
                            departments.push(records[i]._id);
                        }
                    }
                    returnFun(departments);
                }
            );
        };

        function getAllChildDepartmentIds(departmentIds, returnFun){
            var returnAllIds = departmentIds;
            var resultFun = function(departIds){
                if(departIds.length > 0){
                    returnAllIds = returnAllIds.concat(departIds);
                    getChildDepartmentIds(departIds, resultFun);
                }
                else{
                    returnFun(returnAllIds);
                }
            }
            
            getChildDepartmentIds(departmentIds, resultFun);
        };

        $scope.onDepartmentChange = function(){
            $scope.FocusedRecord = null;
            if($scope.Department){
                getAllChildDepartmentIds([$scope.Department._id], function(departmentIds){
                    //通过部门找工位
                    $scope.Module.WorkLocation.find(
                        {
                            Department: {$in: departmentIds}
                        },
                        null, null, function(wRecords){
                            var wRecordIds = [];
                            if(wRecords.length > 0){
                                for(var i=0; i<wRecords.length; i++){
                                    wRecordIds.push(wRecords[i]._id);
                                }
                                //通过工位找终端
                                $scope.Module.StationTerminal.find(
                                    {
                                        WorkLocation: {$in: wRecordIds}
                                    },
                                    null, [{path: 'Terminal'}, {path: 'WorkLocation'}],
                                    function(stRecords){
                                        findDeviceMonitorInfos(stRecords);
                                    }
                                );
                            }
                            else{
                                findDeviceMonitorInfos([]);
                            }                            
                        }
                    );
                });
            }
            else{
                displayRecords = [];
                displayTerminals();
            }
        };

        $scope.terminalClick = function(record){
            $scope.FocusedRecord = record;

            //从工位作业绑定记录表查找作业
            if(!$scope.FocusedRecord.Work){
                $scope.Module.StationWork.find(
                    {
                        WorkLocation: record.WorkLocation._id
                    },
                    null, {path: 'Work', select: 'Name'},
                    function(swRecords){
                        if(swRecords.length > 0){
                            $scope.FocusedRecord.Work = swRecords[0].Work;
                        }
                    }
                );
            }
        };

        $scope.ImgWidth = 60;
        $scope.ImgHeight = 60;
        $scope.DivWidth = $scope.ImgWidth + 20;
        $scope.DivHeight = $scope.ImgHeight + 30;
        $scope.TerminalsDivHeight = 0;
        $scope.Datas = [];

        $scope.ConnectImg = "Scan0.png";
        $scope.AnalyzeImg = "Scan1.png";
        $scope.NormalImg = "Scan2.png";

        var displayRecords = [];     //用来记录要显示的所有记录
        var findDeviceMonitorInfos = function(stRecords){
            if(stRecords.length > 0){
                var connectRecords = [];
                var analyzeRecords = [];
                var returnRecords = [];
                var uniqueIDs = [];
                for(var i=0; i<stRecords.length; i++){
                    if(stRecords[i].Terminal.IsEffective === true && stRecords[i].Terminal.Type == CBOEnum.TerminalType.WiFi.Value){
                        var date = new Date();
                        date.setSeconds(date.getSeconds() - 120 * 30 * 24 * 30);
                        var date2 = stRecords[i].Terminal.LastRequestDate ? new Date(stRecords[i].Terminal.LastRequestDate) : BaseConst.DateTime.Min;
                        if(date.getTime() >= date2.getTime()){          //连接超时
                            stRecords[i].Terminal._Img = $scope.ConnectImg;
                            connectRecords = connectRecords.concat(stRecords.splice(i, 1));
                            i--;
                        }
                        else{   //正常或者解析异常
                            uniqueIDs.push(stRecords[i].Terminal.UniqueID);
                            stRecords[i].Terminal._Img = $scope.NormalImg;
                        }
                    }
                    else{
                        stRecords.splice(i, 1);
                        i--;
                    }
                }

                if(uniqueIDs.length > 0){
                    //查解析异常
                    //条件还未确认，只取第一个
                    var condition = {TerminalUniqueID: {$in: uniqueIDs}, IsProcess: {$ne: true}, ExecuteResult: CBOEnum.ExecuteResult.AnalyzeException.Value};
                    findDeviceMonitor(condition).then(function(dmRecords){
                        for(var i=0; i<dmRecords.length; i++){
                            for(var j=0; j<stRecords.length; j++){
                                if(dmRecords[i].TerminalUniqueID == stRecords[j].Terminal.UniqueID){
                                    stRecords[i].Terminal._Img = $scope.AnalyzeImg;
                                    stRecords[i].Terminal.ExceptionInfo = dmRecords[i].ExceptionInfo;
                                    analyzeRecords = analyzeRecords.concat(stRecords.splice(j, 1));
                                    break;
                                }
                            }
                        }

                        displayRecords = connectRecords.concat(analyzeRecords).concat(stRecords);
                        displayTerminals();
                        $scope.$digest();
                    }).catch(function(err){
                        BaseFunction.errFun(err);
                    });
                }
                else{
                    displayRecords = connectRecords;
                    displayTerminals();
                }
            }
            else{
                displayRecords = [];
                displayTerminals();
            }
        };
        var findDeviceMonitor = function(condition){
            var promise = new Promise(function(resolve, reject) {
                //条件还未确认，只取第一个
                $scope.Module.DeviceMonitor.find(condition, 
                    {RequestTime: 1}, 
                    null,
                    function(dmRecords){
                        resolve(dmRecords);
                    },
                    function(err){
                        reject(err);
                    }
                );
            });
            return promise;
        };

        var columnLength = 0;   //每行显示个数
        var divViewWidth = 0;
        var compute = function(){
            divViewWidth = document.getElementById('headId').parentElement.offsetWidth;
            var divViewHeight = document.getElementById('headId').parentElement.offsetHeight;
            $scope.TerminalsDivHeight = divViewHeight - document.getElementById('headId').offsetHeight - 
                        document.getElementById('headId').parentElement.children[2].offsetHeight;

            //计算每行显示多少个
            columnLength = parseInt(divViewWidth / $scope.DivWidth);
            if(columnLength == 0){
                columnLength++;
            }
        };
        var displayTerminals = function(){
            var rowLength = Math.ceil(displayRecords.length / columnLength);   //行数
            if(columnLength > 1 && rowLength * $scope.DivHeight > $scope.TerminalsDivHeight){   //如果出现滚动条
                if(columnLength * $scope.DivWidth + 20 > divViewWidth){
                    columnLength--;
                }
            }
            $scope.Datas = [];
            for(var i=0; i<rowLength; i++){
                var rowData = displayRecords.slice(i * columnLength, (i + 1) * columnLength);
                $scope.Datas.push(rowData);
            }
        };

        var timer = null;
        angular.element(window).bind( "resize", function() {
            if(timer == null){
                timer = setTimeout(function(){
                    timer = null;
                    compute();
                    displayTerminals();
                    $scope.$digest();
                }, 500);
            }
        });
        compute();

        $scope.btnTerminalException = function(){
            $scope.Module.DeviceMonitor.load(
                {
                    ExecuteResult: {$ne: 0},
                    TerminalUniqueID: $scope.FocusedRecord.Terminal.UniqueID
                }, 
                {RequestTime: 1}, 
                null,
                function(dmRecords){
                    resolve(dmRecords);
                }
            );
        };
    }
]);